/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2021-10-30 10:40:37
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2024-03-13 22:04:34
 */
import router from './router'
import store from './store'
import Cookies from 'js-cookie'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken, isWeChatBrowser
} from '@/utils/auth' // get token from cookie
import { config } from '@/utils/publicUtil'
import getPageTitle from '@/utils/get-page-title'
import { getsignup } from '@/api/user.js'
import { getAuthUrl } from './views/diandi_subscription/wxmp/api/wx-account-fans'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/register', '/forget', '/qcord'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  console.log('hasToken', hasToken, to.path.indexOf('login'))
  if (hasToken) {
    await store.dispatch('user/changeSite', config.siteUrl, config.bmapAk)
    if (to.path.indexOf('login') !== -1) {
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      await resolvePermissionRoute(to, next)
    }
  } else {
    if (isWeChatBrowser()) {
      await resolveWeChatBrowser(to, next)
    } else {
      await resolveNonWeChatBrowser(to, next)
    }
  }

  // Helper functions to keep main logic clean
  async function resolvePermissionRoute(to, next) {
    const permission_routes = store.getters.permission_routes &&
        store.getters.permission_routes.length > 0 &&
        store.getters.LeftMenu.length > 0

    if (Cookies.get('is_roles') && permission_routes) {
      const { user } = await store.dispatch('user/getInfo', window.location.host)
      if (!user.mobile && to.path !== '/profile/bind') {
        /**
         * 用户资料校验强制拦截
         */
        next({ path: '/profile/bind' })
      } else {
        next()
      }
      NProgress.done()
    } else {
      try {
        const { roles } = await store.dispatch('user/getInfo', window.location.host)
        await store.dispatch('user/setRoles', roles)
        const accessRoutes = await store.dispatch('permission/getMenus')
        router.addRoutes(accessRoutes)
        next({ ...to, replace: true })
      } catch (error) {
        await store.dispatch('user/resetToken')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }

  async function resolveWeChatBrowser(to, next) {
    const code = to.query.code
    if (code) {
      const response = await getsignup({ code })
      console.log('根据code获取用户信息', response)
      if (response && response.code === 200) {
        store.dispatch('user/set_token', response.data.access_token)
        const { roles } = response.data
        await store.dispatch('user/setRoles', roles)
        const accessRoutes = await store.dispatch('permission/getMenus')
        router.addRoutes(accessRoutes)
        if (response.data.user.mobile) {
          next({ path: '/dashboard' })
        } else {
          next({ path: '/profile/bind' })
        }
      } else {
        next(`/login?redirect=${to.path}`)
      }
      NProgress.done()
    } else {
      const fullUrl = window.location.href
      const response = await getAuthUrl({ redirect_url: encodeURI(
        fullUrl
      ) })
      if (response && response.code === 200) {
        // eslint-disable-next-line require-atomic-updates
        window.location.href = response.data.url
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }

  async function resolveNonWeChatBrowser(to, next) {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
